//
//  WFCResetPasswordViewController.m
//  WildFireChat
//
//  Created by Rain on 2022/8/4.
//  Copyright © 2022 WildFireChat. All rights reserved.
//

#import "WFCResetPasswordViewController.h"
#import "AppService.h"
#import "MBProgressHUD.h"
#import "UIColor+YH.h"
#import "UIFont+YH.h"
#import "SDAutoLayout.h"
#import "YGExtendChain.h"
#import "SDAutoLayout.h"

@interface WFCResetPasswordViewController () <UITextFieldDelegate>
@property(nonatomic, strong)UILabel *codeLabel;
@property(nonatomic, strong)UITextField *codePasswordfield;
@property(nonatomic, strong)UIView *codeLine;

@property (strong, nonatomic) UIButton *sendCodeBtn;
@property (nonatomic, strong) NSTimer *countdownTimer;
@property (nonatomic, assign) NSTimeInterval sendCodeTime;

@property(nonatomic, strong)UILabel *label,*hintLabel;
@property(nonatomic, strong)UITextField *passwordfield;
@property(nonatomic, strong)UIView *line;

@property(nonatomic, strong)UILabel *repeatLabel;
@property(nonatomic, strong)UITextField *repeatPasswordField;
@property(nonatomic, strong)UIView *repeatLine;

@property (strong, nonatomic) UIButton *loginBtn;

@end

@implementation WFCResetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置新密码";
    self.title = @"";

    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    CGFloat wsf =  ZmScreenWidth_N()   ;
    CGFloat ws1 = wsf  / 360 * 269;
 
    UIImageView *head = [[UIImageView alloc]init];
    [self.view addSubview:head];
    head.image = [UIImage imageNamed:@"lo_top"];
    head.sd_layout.rightEqualToView(self.view).topEqualToView(self.view).widthIs(ZmScreenWidth_N()).heightIs(ws1);
    
    
    
    UIImageView *lo_hi = [[UIImageView alloc]init];
    [self.view addSubview:lo_hi];
    lo_hi.image = [UIImage imageNamed:@"lo_hi"];
    lo_hi.sd_layout.centerXEqualToView(self.view).topSpaceToView(self.view, 160).widthIs(96).heightIs(96);
    
    
    
    
    UILabel *lab1 = [[UILabel alloc] init ];
    [lab1 setText:@"请设置你的密码"];
    lab1.textAlignment = NSTextAlignmentLeft;
    lab1.font = [UIFont boldSystemFontOfSize:20];
    [self.view addSubview:lab1];
    lab1.sd_layout.centerXEqualToView(lo_hi).topSpaceToView(lo_hi, 20 ).autoHeightRatio(0);
    [lab1 setSingleLineAutoResizeWithMaxWidth:200];
    
    
 
    UIView *view_bag = [[UIView alloc]init];
    [self.view addSubview:view_bag];
    view_bag.sd_layout.leftEqualToView(self.view).topSpaceToView(head, 0).widthIs(ZmScreenWidth_N()).bottomEqualToView(self.view);
    view_bag.sh_chain_extend.backgroundColorClear().roundSize(20);
    
    
    
    
     
    
    self.hintLabel = [[UILabel alloc] init ];
//    [self.hintLabel setText:@"设置密码"];
//    self.hintLabel.textAlignment = NSTextAlignmentLeft;
//    self.hintLabel.font = [UIFont boldSystemFontOfSize:24];
//
//    
    CGFloat inputHeight = 60;
    CGFloat topPos = [WFCUUtilities wf_navigationFullHeight] + 16;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat labelWidth = 72;
//    
//  
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(16, topPos, labelWidth, inputHeight)];
//    self.label.font = [UIFont systemFontOfSize:16];
//    self.label.text = @"设置密码";
    
    
    self.passwordfield = [[UITextField alloc] initWithFrame:CGRectMake(16 + labelWidth + 8, topPos, screenWidth - 16 - labelWidth - 8 - 16, inputHeight)];
    self.passwordfield.placeholder = @"请输入新密码";
    self.passwordfield.delegate = self;
    self.passwordfield.keyboardType = UIKeyboardTypeASCIICapable;
    self.passwordfield.secureTextEntry = YES;
    topPos += inputHeight;
    self.line = [[UIView alloc] initWithFrame:CGRectMake(16, topPos, screenWidth - 16 - 16, 1)];
    self.line.backgroundColor = [UIColor grayColor];
    topPos += 1;
    
    UIView * view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 20)];
    self.passwordfield.leftView = view1;
    self.passwordfield.leftViewMode = UITextFieldViewModeAlways;
    
    UIImageView *img1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"login_2"]];
    [view1 addSubview:img1];
    img1.sd_layout.centerXEqualToView(view1).centerYEqualToView(view1).widthIs(20).heightIs(20);
   
    
    
    
    
    self.passwordfield.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:15];

    topPos += 16;
    self.repeatLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, topPos, labelWidth, inputHeight)];
    self.repeatLabel.font = [UIFont systemFontOfSize:16];
    self.repeatLabel.text = @"再次确认密码";
    
    self.repeatPasswordField = [[UITextField alloc] initWithFrame:CGRectMake(16 + labelWidth + 8, topPos, screenWidth - 16 - labelWidth - 8 - 16, inputHeight)];
    self.repeatPasswordField.placeholder = @"请输入确认密码";
    self.repeatPasswordField.delegate = self;
    self.repeatPasswordField.keyboardType = UIKeyboardTypeASCIICapable;
    self.repeatPasswordField.secureTextEntry = YES;
    
    topPos += inputHeight;
    self.repeatLine = [[UIView alloc] initWithFrame:CGRectMake(16, topPos, screenWidth - 16 - 16, 1)];
    self.repeatLine.backgroundColor = [UIColor grayColor];
    
    self.repeatPasswordField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 20)];
    self.repeatPasswordField.leftViewMode = UITextFieldViewModeAlways;
    self.repeatPasswordField.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:15];

    UIView * view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 20)];
    self.repeatPasswordField.leftView = view2;
    self.repeatPasswordField.leftViewMode = UITextFieldViewModeAlways;
    
    UIImageView *img2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"login_2"]];
    [view2 addSubview:img2];
    img2.sd_layout.centerXEqualToView(view2).centerYEqualToView(view2).widthIs(20).heightIs(20);
   

    
//    [self.view addSubview:self.label];
//    [self.view addSubview:self.passwordfield];
//    [self.view addSubview:self.line];
//    [self.view addSubview:self.repeatLabel];
//    [self.view addSubview:self.repeatPasswordField];
//    [self.view addSubview:self.repeatLine];
    
    
    [view_bag addSubview:self.hintLabel];
    self.hintLabel.sd_layout.leftSpaceToView(view_bag, 30).topSpaceToView(view_bag, 30).autoHeightRatio(0);
    [self.hintLabel setSingleLineAutoResizeWithMaxWidth:ZmScreenWidth_N()];
    
    
    
    UIView *lastV;
    
    if (!self.resetCode.length) {
        
        self.codeLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, topPos, labelWidth, inputHeight)];
        self.codeLabel.font = [UIFont systemFontOfSize:16];
        self.codeLabel.text = @"验证码";
        
        
        self.codePasswordfield = [[UITextField alloc] initWithFrame:CGRectMake(16 + labelWidth + 8, topPos, screenWidth - 16 - labelWidth - 8 - 16-72, inputHeight)];
        self.codePasswordfield.placeholder = @"请输入短信验证码";
        self.codePasswordfield.delegate = self;
        self.codePasswordfield.keyboardType = UIKeyboardTypeASCIICapable;
        
        self.codePasswordfield.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 20)];
        self.codePasswordfield.leftViewMode = UITextFieldViewModeAlways;

        self.codePasswordfield.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:15];

        UIView * view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 20)];
        self.codePasswordfield.leftView = view2;
        self.codePasswordfield.leftViewMode = UITextFieldViewModeAlways;
        
        UIImageView *img2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"login_3"]];
        [view2 addSubview:img2];
        img2.sd_layout.centerXEqualToView(view2).centerYEqualToView(view2).widthIs(20).heightIs(20);
       
        
        self.sendCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(screenWidth - 16 - 72, topPos + (inputHeight - 23)/2, 72, 23)];
        [self.sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.sendCodeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
//        self.sendCodeBtn.layer.borderWidth = 1;
//        self.sendCodeBtn.layer.cornerRadius = 4;
//        self.sendCodeBtn.layer.borderColor = [UIColor colorWithHexString:@"0x191919"].CGColor;
        [self.sendCodeBtn setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];
//        [self.sendCodeBtn setTitleColor:[UIColor colorWithHexString:@"0x171717"] forState:UIControlStateSelected];
        [self.sendCodeBtn addTarget:self action:@selector(onSendCode:) forControlEvents:UIControlEventTouchDown];
//        self.sendCodeBtn.sh_chain_extend.backgroundImage_state([UIImage imageWithColor:[UIColor colorWithHexString:@"#016EFF"]], 0) .backgroundImage_state([UIImage imageWithColor:[UIColor colorWithHexString:@"#D8D8D8"]], UIControlStateDisabled) ;

        topPos += inputHeight;
        self.codeLine = [[UIView alloc] initWithFrame:CGRectMake(16, topPos, screenWidth - 16 - 16, 1)];
        self.codeLine.backgroundColor = [UIColor grayColor];
//        [view_bag addSubview:self.codeLabel];
//        [view_bag addSubview:self.codePasswordfield];
//        [view_bag addSubview:self.codeLine];
//        [view_bag addSubview:self.sendCodeBtn];
        
        
//        [view_bag addSubview:self.codeLabel];
//        self.codeLabel.sd_layout.leftEqualToView(self.hintLabel).topSpaceToView(self.hintLabel, 30).autoHeightRatio(0);
//        [self.codeLabel setSingleLineAutoResizeWithMaxWidth:ZmScreenWidth_N()];

        
        [view_bag addSubview:self.codePasswordfield];
        self.codePasswordfield.sd_layout.leftSpaceToView(view_bag, 30).topSpaceToView(view_bag, 40).heightIs(45).widthIs(ZmScreenWidth_N() - 60);
        self.codePasswordfield.sh_chain_extend.roundSize(5).backgroundColor([UIColor colorWithHexString:@"#F7F7F7"]);

        
    //    [view_bag addSubview:self.passwordLine];
        [view_bag addSubview:self.sendCodeBtn];
        self.sendCodeBtn.sd_layout.rightEqualToView(self.codePasswordfield).widthIs(94).heightIs(45).centerYEqualToView(self.codePasswordfield);
//        self.sendCodeBtn.sh_chain_extend.round();
        
        topPos += 1;
        lastV = self.codePasswordfield;
        topPos += 16;
    }
    
    
    
//    [view_bag addSubview:self.label];
//    self.label.sd_layout.leftEqualToView(self.hintLabel).topSpaceToView(lastV ? lastV : self.hintLabel, lastV ? 15 :30).autoHeightRatio(0);
//    [self.label setSingleLineAutoResizeWithMaxWidth:ZmScreenWidth_N()];
    
    
    [view_bag addSubview:self.passwordfield];
    self.passwordfield.sd_layout.leftSpaceToView(view_bag, 30).topSpaceToView(lastV ? lastV : view_bag, lastV ? 20 : 40).heightIs(45).widthIs(ZmScreenWidth_N() - 60);
    self.passwordfield.sh_chain_extend.roundSize(5).backgroundColor([UIColor colorWithHexString:@"#F7F7F7"]);
    
    
//    [view_bag addSubview:self.userNameLine];
 
//    [view_bag addSubview:passwordContainer];
//    [view_bag addSubview:self.repeatLabel];
//    self.repeatLabel.sd_layout.leftEqualToView(self.hintLabel).topSpaceToView(self.passwordfield, 15).autoHeightRatio(0);
//    [self.repeatLabel setSingleLineAutoResizeWithMaxWidth:ZmScreenWidth_N()];

    
    [view_bag addSubview:self.repeatPasswordField];
    self.repeatPasswordField.sd_layout.leftSpaceToView(view_bag, 30).topSpaceToView(self.passwordfield, 20).heightIs(45).widthIs(ZmScreenWidth_N() - 60);
    self.repeatPasswordField.sh_chain_extend.roundSize(5).backgroundColor([UIColor colorWithHexString:@"#F7F7F7"]);

     
     
    
    
    
    
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(onRightBtn:)];
//    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    self.loginBtn = [[UIButton alloc] init ];
    [self.loginBtn addTarget:self action:@selector(onRightBtn:) forControlEvents:UIControlEventTouchDown];
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.layer.cornerRadius = 5.f;
    [self.loginBtn setTitle:@"完成" forState:UIControlStateNormal];
    self.loginBtn.backgroundColor = [UIColor colorWithHexString:@"#E2E2E2"];
    [self.loginBtn setTitleColor:[UIColor colorWithHexString:@"#A7A7A7"] forState:UIControlStateNormal];
    self.loginBtn.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleMedium size:16];
    self.loginBtn.enabled = NO;
//    [self.view addSubview:self.loginBtn];
//    self.loginBtn.sd_layout.centerXEqualToView(self.view).heightIs(50).topSpaceToView(self.repeatLine, 40).widthIs(ZmScreenWidth_N() - 32 - 50);
//    
    
   
   [view_bag addSubview:self.loginBtn];
   self.loginBtn.sd_layout.topSpaceToView(self.repeatPasswordField, 85).heightIs(45).widthIs(ZmScreenWidth_N() - 60).centerXEqualToView(view_bag);
   self.loginBtn.sh_chain_extend.roundSize(5);
   
   
   

    ///<
//    self.navigationController.navigationBar.barTintColor  = [UIColor whiteColor];
//
//    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];
//
////    // 设置导航栏item指示色
//    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
//     //  设置导航栏标题颜色与大小
//    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:17]};
//    //设置导航栏背景颜色
//    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
//        UILabel *titleLabel         = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
//
//        titleLabel.text             = @"123";
//
//        titleLabel.font             = [UIFont boldSystemFontOfSize:20.f];
//
//        titleLabel.textAlignment    = NSTextAlignmentCenter;
//
//        titleLabel.textColor        = [UIColor whiteColor];
//
//        self.navigationItem.titleView = titleLabel;
    
    
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
//    
//    // 设置导航栏背景色
//    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
//     
//    // 如果需要支持iOS 13及以上的版本，请使用新的API
//    if (@available(iOS 13.0, *)) {
//        self.navigationController.navigationBar.backgroundColor = [UIColor colorWithHexString:@"#016EFF"];
//        self.navigationController.navigationBar.standardAppearance.backgroundColor = [UIColor colorWithHexString:@"#016EFF"];
//        self.navigationController.navigationBar.compactAppearance.backgroundColor = [UIColor colorWithHexString:@"#016EFF"];
//        self.navigationController.navigationBar.scrollEdgeAppearance.backgroundColor = [UIColor colorWithHexString:@"#016EFF"];
//    }
//
//    self.navigationController.navigationBar.tintColor  = [UIColor whiteColor]; ///<.标题颜色>
    ///<
}

- (void)onSendCode:(id)sender {
    self.sendCodeBtn.enabled = NO;
    [self.sendCodeBtn setTitle:@"短信发送中" forState:UIControlStateNormal];
    __weak typeof(self)ws = self;
    [[AppService sharedAppService] sendResetCode:nil success:^{
       [ws sendCodeDone:YES];
    } error:^(NSString * _Nonnull message) {
        [ws sendCodeDone:NO];
    }];
}

- (void)sendCodeDone:(BOOL)success {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (success) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = @"发送成功";
         //   //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
            self.sendCodeTime = [NSDate date].timeIntervalSince1970;
            self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                                                target:self
                                                                 selector:@selector(updateCountdown:)
                                                              userInfo:nil
                                                               repeats:YES];
            [self.countdownTimer fire];
            
            
            [hud hideAnimated:YES afterDelay:1.f];
        } else {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = @"发送失败";
          //  //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
            [hud hideAnimated:YES afterDelay:1.f];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                self.sendCodeBtn.enabled = YES;
            });
        }
    });
}

- (void)updateCountdown:(id)sender {
    int second = (int)([NSDate date].timeIntervalSince1970 - self.sendCodeTime);
    [self.sendCodeBtn setTitle:[NSString stringWithFormat:@"%ds", 60-second] forState:UIControlStateNormal];
    if (second >= 60) {
        [self.countdownTimer invalidate];
        self.countdownTimer = nil;
        [self.sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.sendCodeBtn.enabled = YES;
    }
}

- (void)onRightBtn:(id)sender {
    NSString *password = self.passwordfield.text;
    NSString *code = self.resetCode.length ? self.resetCode : self.codePasswordfield.text;
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"保存中...";
    [hud showAnimated:YES];
    __weak typeof(self)ws = self;
    [[AppService sharedAppService] resetPassword:nil code:code newPassword:password success:^{
        NSLog(@"change success");
        [hud hideAnimated:YES];
        [ws.navigationController popViewControllerAnimated:YES];
    } error:^(int errCode, NSString * _Nonnull message) {
        NSLog(@"change failure");
        [hud hideAnimated:YES];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = @"保存失败";
        //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
        [hud hideAnimated:YES afterDelay:1.f];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [ws.navigationController popViewControllerAnimated:YES];
        });
        
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSString *password = self.passwordfield.text;
    NSString *repeat = self.repeatPasswordField.text;
    NSString *code = self.resetCode.length ? self.resetCode : self.codePasswordfield.text;
    
    if (password.length && [password isEqualToString:repeat] && code.length >= 4) {
        [self onRightBtn:nil];
    }
    return NO;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.passwordfield) {
        self.line.backgroundColor = [UIColor colorWithHexString:@"0xd4d4d4"];
        self.repeatLine.backgroundColor = [UIColor grayColor];
    } else if (textField == self.repeatPasswordField) {
        self.line.backgroundColor = [UIColor grayColor];
        self.repeatLine.backgroundColor = [UIColor colorWithHexString:@"0xd4d4d4"];
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *txt = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSString *anotherTxt = self.passwordfield == textField ? self.repeatPasswordField.text : self.passwordfield.text;
    NSString *code = self.resetCode.length ? self.resetCode : self.codePasswordfield.text;
    
//    if(anotherTxt.length && [anotherTxt isEqualToString:txt] && code.length) {
//        self.loginBtn.enabled = YES;
//    } else {
//        self.loginBtn.enabled = NO;
//    }
    if(anotherTxt.length && [anotherTxt isEqualToString:txt] && code.length) {
        
        [self.loginBtn setBackgroundColor:[UIColor colorWithHexString:@"#016EFF"]];
        [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.loginBtn.enabled = YES;
    } else {
        [self.loginBtn setBackgroundColor:[UIColor colorWithHexString:@"#E2E2E2"]];
        [self.loginBtn setTitleColor:[UIColor colorWithHexString:@"#A7A7A7"] forState:UIControlStateNormal];
        
        self.loginBtn.enabled = NO;
    }
    
    
    return YES;
}

@end
